package com.test.jbpm.web;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.jbpm.PagerContext;


public class PagerFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("start"));
		}catch(Exception e) {
		}
		int pageSize = 0;
		if (request.getParameter("limit") == null) {
			pageSize = Integer.parseInt(request.getSession().getServletContext().getInitParameter("pageSize"));
		}else {
			pageSize = Integer.parseInt(request.getParameter("limit"));
		}
		//将offset和pageSize设置到ThreadLocal中
		PagerContext.setOffset(offset);
		PagerContext.setPageSize(pageSize);
		try {
			//继续执行
			filterChain.doFilter(request, response);
		}finally {
			//从ThreadLocal中清除
			PagerContext.removeOffset();
			PagerContext.removePageSize();
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}